import { Menu, MenuProps } from 'antd'
import { useLocation, useNavigate } from 'react-router-dom'
import { managementMenu } from '@/router'
import { useEffect, useState } from 'react'

type MenuItem = Required<MenuProps>['items'][number]

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem
}

function MyMenu() {
  const navigate = useNavigate()
  const items: MenuItem[] = managementMenu.map((item: any) => {
    let children: any = []
    if (item.children) {
      children = item.children.map((childItem: any) => {
        if(childItem.handle.noShow){
          return null
        }
        return getItem(
          childItem.handle.name,
          `${item.path}/${childItem.path}`,
          childItem.handle.icon
        )
      })
    }
    return getItem(item.handle.name, item.path, item.handle.icon, children.length ? children : undefined)
  })
  const [curSelectKey, setCurSelectKey] = useState<string[]>([])

  const keySelected = ({ key, keyPath, selectedKeys, domEvent }: any) => {
    setCurSelectKey(key)
    navigate(`${key}`)
  }
  const location = useLocation()
  useEffect(() => {
    setCurSelectKey([
      location.pathname.slice(location.pathname.lastIndexOf('/') + 1),
    ])
  }, [location])

  return (
    <Menu
      mode="inline"
      items={items}
      onSelect={keySelected}
      selectedKeys={curSelectKey}
    />
  )
}

export default MyMenu
